# -*- coding: utf-8 
import json, urllib
from math import *
GEOCODE_BASE_URL = 'http://maps.googleapis.com/maps/api/geocode/json?address='

def format_adresse(adresse):
    adresse_formatee = adresse.replace(" ", "+")
    adresse_formatee = adresse_formatee.replace("é", "e")
    adresse_formatee = adresse_formatee.replace("è", "e")
    adresse_formatee = adresse_formatee.replace("à", "a")
    return adresse_formatee

def format_coordonnees(lat, lng):
    lat_str = str(lat)
    lat_form = lat_str.replace(',', '.')
    lng_str = str(lng)
    lng_form = lng_str.replace(',', '.')
    return [lat_form, lng_form]
    
def geocode(adresse):
    url = GEOCODE_BASE_URL + adresse + '&sensor=false&region=fr'
    result = json.load(urllib.urlopen(url))
    if result['status']=="OK":
        resultat = result['results'][0]
        lat = resultat['geometry']['location']['lat']
        lng = resultat['geometry']['location']['lng']
        G = [lat, lng]
        return G
    else:
        return False

def barycentre(tab): 
    # rend le barycentre des invités à partir du tableau de leurs coordonnées respectives
    lat_bar = 0
    long_bar = 0
    for i in range(0,len(tab)):
        lat_bar += tab[i][0]
        long_bar += tab[i][1]
    lat_bar = lat_bar/len(tab)
    long_bar = long_bar/len(tab)
    return [lat_bar, long_bar]

def distance(lat1, lon1, lat2, lon2):
    # rend la distance entre deux points à partir de leurs coordonneés GPS
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * atan2(sqrt(a), sqrt(1-a)) 
    km = 6367 * c
    return km 